<template>
  <div ref="chartRef" class="bar-chart-container"></div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch, computed } from 'vue'
import * as echarts from 'echarts'

// 定义 props
const props = defineProps({
  // 图表数据
  data: {
    type: Array,
    required: true,
    validator: (value) => {
      return value.every(item => 'name' in item && 'value' in item)
    }
  },
  // 图表标题
  title: {
    type: String,
    default: ''
  },
  // X轴名称
  xAxisName: {
    type: String,
    default: ''
  },
  // Y轴名称
  yAxisName: {
    type: String,
    default: ''
  },
  // 是否显示图例
  showLegend: {
    type: Boolean,
    default: false
  },
  // 是否显示数据标签
  showLabel: {
    type: Boolean,
    default: true
  },
  // 柱形颜色
  color: {
    type: String,
    default: '#5470c6'
  },
  // 柱形宽度
  barWidth: {
    type: String,
    default: '60%'
  },
  // 是否显示网格线
  showGrid: {
    type: Boolean,
    default: true
  },
  // 是否平滑过渡动画
  smooth: {
    type: Boolean,
    default: true
  },
  // Y轴最小值
  yMin: {
    type: Number,
    default: null
  },
  // Y轴最大值
  yMax: {
    type: Number,
    default: null
  }
})

const chartRef = ref(null)
let chartInstance = null

// 计算Y轴最大值 (自动调整或使用props传入的值)
const yAxisMax = computed(() => {
  if (props.yMax !== null) return props.yMax
  const maxValue = Math.max(...props.data.map(item => item.value))
  return maxValue * 1.2 // 默认留出20%空间
})

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return
  
  // 如果已有实例则先销毁
  if (chartInstance) {
    chartInstance.dispose()
  }
  
  chartInstance = echarts.init(chartRef.value)
  updateChart()
}

// 更新图表配置
const updateChart = () => {
  if (!chartInstance) return
  
  const option = {
    title: {
      text: props.title,
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: (params) => {
        const data = params[0]
        return `
          <div style="font-weight:bold">${data.name}</div>
          <div>${props.yName || '值'}: ${data.value}</div>
        `
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: props.title ? '15%' : '10%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: props.data.map(item => item.name),
      axisLabel: {
        rotate: props.data.length > 8 ? 45 : 0, // 数据多时旋转标签
        interval: 0 // 强制显示所有标签
      },
      axisLine: {
        lineStyle: {
          color: '#999'
        }
      },
      name: props.xAxisName,
      nameLocation: 'middle',
      nameGap: 30
    },
    yAxis: {
      type: 'value',
      name: props.yAxisName,
      min: props.yMin,
      max: yAxisMax.value,
      axisLine: {
        show: true,
        lineStyle: {
          color: '#999'
        }
      },
      splitLine: {
        show: props.showGrid,
        lineStyle: {
          type: 'dashed'
        }
      }
    },
    series: [
      {
        name: props.title || '数据',
        type: 'bar',
        barWidth: props.barWidth,
        data: props.data.map(item => item.value),
        itemStyle: {
          color: props.color,
          borderRadius: [4, 4, 0, 0] // 顶部圆角
        },
        label: {
          show: props.showLabel,
          position: 'top',
          formatter: '{c}'
        },
        animation: props.smooth,
        animationEasing: 'elasticOut',
        animationDelay: (idx) => idx * 100
      }
    ]
  }
  
  chartInstance.setOption(option)
}

// 响应式调整大小
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize()
  }
}

// 生命周期钩子
onMounted(() => {
  initChart()
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  if (chartInstance) {
    window.removeEventListener('resize', handleResize)
    chartInstance.dispose()
    chartInstance = null
  }
})

// 监听数据变化
watch(() => props.data, () => {
  updateChart()
}, { deep: true })

// 监听其他属性变化
watch(() => [
  props.title,
  props.xAxisName,
  props.yAxisName,
  props.showLegend,
  props.showLabel,
  props.color,
  props.barWidth,
  props.showGrid,
  props.smooth,
  props.yMin,
  props.yMax
], () => {
  updateChart()
})
</script>

<style scoped>
.bar-chart-container {
  width: 100%;
  height: 100%;
}
</style>